<?php
namespace haibao\www\data\message;

class MessageBoxUnReg extends \haibao\www\data\BaseMysql{

    public function __construct(){
        parent::__construct('\haibao\www\model\data\message\MessageBoxUnReg');
		$this->setConfig( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_USER );
    }
    
    public function updateMessageReadStatus($messageIds,$status){
    	 
    	$messageIds = (array)$messageIds;
    	$messageIdStr = implode(',', $messageIds);
    	$str = preg_replace('/(\d+)/', '%s', $messageIdStr);
    	$sql = 'update MessageBoxUnReg set IsRead=%s where Id in ('.$str.')';
    	array_unshift($messageIds, $status);
    	$this->query($sql,$messageIds);
    	 
    }
   
    
    public function mergeUserData($userId,$unRegUserId){
    	
    	$strArr = $valArr = array();
    	$sql = 'select FromUserId,MessageType,MessageData FROM MessageBoxUnReg where ToUserId = %s and MessageType = %s';
    	$result = $this->query($sql,array($unRegUserId,\haibao\www\model\data\message\MessageBoxUnReg::MESSAGE_TYPE_COMMENT));
    	$sql = "insert into MessageBox (FromUserId,ToUserId,MessageType,MessageData,IsRead,CreateTime) VALUES";
    	$sqlArr = $valArr = array();
    	while ($result->fetch_assoc()){
			array_push($sqlArr,'(%s,%s,%s,%s,%s,%s)');
			$fromUserId = $result->getData('FromUserId');
			if(strlen($result->getData('FromUserId')) == 36){
				$fromUserId = null;
			}
			array_push($valArr,$fromUserId);
			array_push($valArr,$userId);
			array_push($valArr,$result->getData('MessageType'));
			array_push($valArr,$result->getData('MessageData'));
			array_push($valArr,\haibao\www\model\data\message\MessageBoxUnReg::READ_HAVE);
			array_push($valArr,new \DateTime());
    	}
    	if($sqlArr && $valArr){
    		$sql .= implode(',',$sqlArr);
    		$this->query($sql,$valArr);
    		
    		// 将游客数据做删除处理
    		$sql = 'delete from MessageBoxUnReg where ToUserId=%s and MessageType=%s';
    		$this->query($sql,array($unRegUserId,\haibao\www\model\data\message\MessageBoxUnReg::MESSAGE_TYPE_COMMENT));
    	}
    }
    
    public function deleteExpireMessage($date,$table = 'MessageBoxUnReg'){

    	$sql = 'delete from '.$table.' where CreateTime<=%s';
    	$this->query($sql,array($date));
    }
}